package com.zhoug.zmui.group;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.zhoug.common.utils.LogUtils;
import com.zhoug.zmui.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.PrimitiveIterator;

import androidx.annotation.Nullable;

/**
 * 流动布局,childView水平排列,自动换行换行,
 * <p>
 * TextView android:gravity="center"无效时要设置android:singleLine="true"
 *发布版一定要改成false,否则会绘制padding边框
 * @Author 35574
 * @Date 2020/11/2
 * @Description
 */
public class ZMUIFlowViewGroup extends ViewGroup {
    private static final String TAG = ">>>ZMUIFlowViewGroup";
    private static final boolean debug = false;//发布版一定要改成false,否则会绘制padding边框
    /**
     * 对齐方式 right 0，left 1，center 2
     * {@link Gravity#START,Gravity#END,Gravity#CENTER_HORIZONTAL}
     */
    private int gravity;
    /**
     * 水平间距,单位px
     */
    private int horizontalSpace;
    /**
     * 垂直间距,单位px
     */
    private int verticalSpace;
    /**
     * 是否自动填满
     * 充满当前行时,每个ChildView平分剩余的空间
     */
    private boolean isFull;

    public ZMUIFlowViewGroup(Context context) {
        this(context, null);
    }

    public ZMUIFlowViewGroup(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZMUIFlowViewGroup(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }


    private void init(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ZMUIFlowViewGroup, defStyleAttr, R.style.zmui_style_ZMUIFlowViewGroup);
        gravity = a.getInt(R.styleable.ZMUIFlowViewGroup_android_gravity, Gravity.START);
        horizontalSpace = a.getDimensionPixelOffset(R.styleable.ZMUIFlowViewGroup_zmui_horizontalSpace, 0);
        verticalSpace = a.getDimensionPixelOffset(R.styleable.ZMUIFlowViewGroup_zmui_verticalSpace, 0);
        isFull = a.getBoolean(R.styleable.ZMUIFlowViewGroup_zmui_isFull, false);

        a.recycle();

    }

    private List<String> mRowRowColumn = new ArrayList<>();

    private void setRowColumn(int childPosition, int row, int column) {
        mRowRowColumn.add(row + "-" + column + "-" + childPosition);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mRowRowColumn.clear();
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        LogUtils.d(TAG, "onMeasure:widthSize=" + widthSize + ",heightSize=" + heightSize);

        int childCount = getChildCount();
        int totalChildHeight = 0;//所有child占用的高度
        int rowMaxWidth = 0;//一行占用的最大宽度
        //最大宽度限制
        if (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.EXACTLY) {
            //child可以占用的最大宽度
            int maxContentWidth = widthSize - getPaddingStart() - getPaddingEnd();
            if (debug) {
                LogUtils.d(TAG, "maxContentWidth:" + maxContentWidth);
            }
            int rowIndex = 0;//行
            int colIndex = 0;//列
            int rowMaxHeight = 0;//一行占用的最大高度
            int rowWidth = 0;//每行的宽度
            for (int childPosition = 0; childPosition < childCount; childPosition++) {
                View child = getChildAt(childPosition);
                if (child.getVisibility() != GONE) {
                    //测量child
                    measureChild(child, MeasureSpec.makeMeasureSpec(maxContentWidth, MeasureSpec.AT_MOST), heightMeasureSpec);
                    int childMeasuredWidth = child.getMeasuredWidth();
                    int childMeasuredHeight = child.getMeasuredHeight();
                    if (debug) {
                        LogUtils.d(TAG, childPosition + "=>childMeasuredWidth:" + childMeasuredWidth + ",childMeasuredHeight=" + childMeasuredHeight);
                    }

                    if (colIndex == 0) {
                        //第一列
                        setRowColumn(childPosition, rowIndex, colIndex);
                        rowWidth = childMeasuredWidth;
                        rowMaxHeight = childMeasuredHeight;
                    } else {
                        if (rowWidth+horizontalSpace + childMeasuredWidth > maxContentWidth) {
                            //换行
                            totalChildHeight += rowMaxHeight + verticalSpace;//加上上一行高度
                            rowMaxWidth=Math.max(rowMaxWidth,rowWidth);
                            rowIndex++;
                            colIndex = 0;
                            setRowColumn(childPosition, rowIndex, colIndex);
                            rowWidth = childMeasuredWidth;
                            rowMaxHeight = childMeasuredHeight;
                        } else {
                            //不换行
                            setRowColumn(childPosition, rowIndex, colIndex);
                            rowWidth +=  horizontalSpace+childMeasuredWidth;
                            rowMaxHeight = Math.max(rowMaxHeight, childMeasuredHeight);
                        }
                    }
                    colIndex++;
                    if (debug) {
                        LogUtils.d(TAG, String.format(Locale.CANADA, "row:%d=>rowWidth=%d", rowIndex, rowWidth));
                    }
                }
            }
            totalChildHeight += rowMaxHeight ;//加上上一行高度
            rowMaxWidth=Math.max(rowMaxWidth,rowWidth);


        } else {
            //UNSPECIFIED 宽度无限
            if (debug) {
                LogUtils.d(TAG, "onMeasure:UNSPECIFIED 宽度无限 1行");
            }
            int colIndex = 0;
            for (int childPosition = 0; childPosition < childCount; childPosition++) {
                View child = getChildAt(childPosition);
                if (child.getVisibility() != GONE) {
                    measureChild(child, widthMeasureSpec, heightMeasureSpec);
                    int childMeasuredWidth = child.getMeasuredWidth();
                    int childMeasuredHeight = child.getMeasuredHeight();
                    if (debug) {
                        LogUtils.d(TAG, childPosition + "=>childMeasuredWidth:" + childMeasuredWidth + ",childMeasuredHeight=" + childMeasuredHeight);
                    }
                    totalChildHeight = Math.max(totalChildHeight, childMeasuredHeight);
                    rowMaxWidth += childMeasuredWidth + horizontalSpace;
                    setRowColumn(childPosition, 0, colIndex);
                    colIndex++;
                }
            }
        }

        int size = mRowRowColumn.size();
        for (int i = 0; i < size; i++) {
            String rowRowColumn = mRowRowColumn.get(i);
            String[] split = rowRowColumn.split("-");
            int row = Integer.parseInt(split[0]);
            int column = Integer.parseInt(split[1]);
            int childPosition = Integer.parseInt(split[2]);
            if (debug) {
                LogUtils.d(TAG, "onMeasure:row=" + row + ",column=" + column + ",childPosition=" + childPosition);
            }
        }
        if (debug) {
            LogUtils.d(TAG, "onMeasure:rowMaxWidth=" + rowMaxWidth + ",totalChildHeight=" + totalChildHeight);
        }
        int width;
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else if (widthMode == MeasureSpec.AT_MOST) {
            width = Math.min(widthSize, rowMaxWidth + getPaddingStart() + getPaddingEnd());
        } else {
            width = rowMaxWidth + getPaddingStart() + getPaddingEnd();
        }
        int height;
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else if (heightMode == MeasureSpec.AT_MOST) {
            height = Math.min(heightSize, totalChildHeight + getPaddingTop() + getPaddingBottom());
        } else {
            height = totalChildHeight + getPaddingTop() + getPaddingBottom();
        }
        if (debug) {
            LogUtils.d(TAG, "onMeasure:width=" + width + ",height=" + height);
        }
        setMeasuredDimension(width, height);
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int measuredWidth = getMeasuredWidth();
        int measuredHeight = getMeasuredHeight();
        if (debug) {
            LogUtils.d(TAG, "onLayout:measuredWidth=" + measuredWidth + ",measuredHeight=" + measuredHeight);
        }
        int maxRight=measuredWidth-getPaddingEnd();//child的最大有坐标
        int top = getPaddingTop();
        int left = getPaddingStart();
        int rowMaxHeight = 0;//一行的高度
        int rowIndex = 0;
        int colIndex = 0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                int childMeasuredWidth = child.getMeasuredWidth();
                int childMeasuredHeight = child.getMeasuredHeight();
                if (colIndex == 0) {
                    child.layout(left, top, left + childMeasuredWidth, top + childMeasuredHeight);
                    colIndex++;
                    left += childMeasuredWidth + horizontalSpace;
                    rowMaxHeight = Math.max(rowMaxHeight, childMeasuredHeight);
                } else {
                    if (left + childMeasuredWidth > maxRight) {
                        //换行
                        colIndex = 0;
                        left = getPaddingStart();
                        top += rowMaxHeight + verticalSpace;
                        child.layout(left, top, left + childMeasuredWidth, top + childMeasuredHeight);
                        colIndex++;
                        left += childMeasuredWidth + horizontalSpace;
                        rowMaxHeight = childMeasuredHeight;
                    } else {
                        //不换行
                        child.layout(left, top, left + childMeasuredWidth, top + childMeasuredHeight);
                        colIndex++;
                        left += childMeasuredWidth + horizontalSpace;
                        rowMaxHeight = Math.max(rowMaxHeight, childMeasuredHeight);
                    }
                }
            }

        }

    }

    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if(debug){
            int paddingStart = getPaddingStart();
            int paddingEnd = getPaddingEnd();
            int paddingTop = getPaddingTop();
            int paddingBottom = getPaddingBottom();

            mPaint.setColor(Color.BLUE);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(1);
            canvas.drawRect(paddingStart, paddingTop, canvas.getWidth() - paddingEnd, canvas.getHeight() - paddingBottom, mPaint);
        }

    }

}
